<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElInput, ElButton, ElForm, ElFormItem, ElCard, ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
import { login } from '../api/auth'


const form = reactive({
  email: '',
  password: ''
})
const loading = ref(false)
const router = useRouter()
const formRef = ref<FormInstance>()


const rules: FormRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

const onLogin = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    loading.value = true
    try {
      const res = await login({ email: form.email, password: form.password })
      if (res.data && res.data.code === 200) {
        // 存储token
        localStorage.setItem('accessToken', res.data.data.accessToken)
        
        // 存储用户信息、角色和权限
        localStorage.setItem('userInfo', JSON.stringify({
          _id: res.data.data._id,
          username: res.data.data.username,
          email: res.data.data.email
        }))
        localStorage.setItem('userRoles', JSON.stringify(res.data.data.roles))
        localStorage.setItem('userPermissions', JSON.stringify(res.data.data.permissions))
        
        ElMessage.success('登录成功')
        
        // 根据角色决定重定向路径
        const isAdmin = res.data.data.roles.some((role: any) => role.name === 'admin')
        
        // 如果是管理员，直接进入管理界面，否则进入商户首页
        if (isAdmin) {
          router.push('/admin')
        } else {
          router.push('/home')
        }
      } else {
        ElMessage.error(res.data?.message || '登录失败')
      }
    } catch (err: any) {
      ElMessage.error(err.response?.data?.message || '登录失败')
    } finally {
      loading.value = false
    }
  })
}

const goToRegister = () => {
  router.push('/register')
}
</script>

<template>
  <div class="login-bg">
    <el-card class="login-card">
      <div class="login-title">
        <span style="color:#e1251b;font-weight:bold;font-size:2rem;">Zeno</span><span style="color:#e1251b;font-size:2rem;">电商平台</span>
      </div>
      <el-form :model="form" :rules="rules" ref="formRef" @submit.prevent="onLogin">
        <el-form-item prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" prefix-icon="el-icon-message" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" prefix-icon="el-icon-lock" />
        </el-form-item>
        <el-form-item>
          <el-button type="danger" style="width:100%;font-size:1.2rem;background: #e1251b;" :loading="loading" @click="onLogin">登 录</el-button>
        </el-form-item>
        <div class="register-link">
          <el-link type="primary" @click="goToRegister">没有账号？立即注册</el-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped>
.login-bg {
  min-height: 100vh;
  background: #f5f6fa;
  display: flex;
  align-items: center;
  justify-content: center;
}
.login-card {
  width: 400px;
  padding: 40px 32px 32px 32px;
  box-sizing: border-box;
}
.login-title {
  text-align: center;
  margin-bottom: 32px;
}
.register-link {
  text-align: center;
  margin-top: 16px;
}
</style> 